import { Request, Response, NextFunction } from "express";
import { Injectable, Logger, NestMiddleware } from "@nestjs/common";
import * as chalk from "chalk";

@Injectable()
export class LoggerMiddleware implements NestMiddleware {
  private logger = new Logger("HTTP");
  use(request: Request, response: Response, next: NextFunction): void {
    const { ip, method, originalUrl } = request;
    const userAgent = request.get("user-agent") || "";
    const start = Date.now();

    response.on("finish", () => {
      const { statusCode } = response;
      const ms = Date.now() - start;
      const contentLength = response.get("content-length");
      // console.log(`-------------------------------------------------`);
      this.logger.log(
        `${chalk.cyan(method)} ${originalUrl} ${
          statusCode === 200 ? chalk.grey(statusCode) : chalk.red(statusCode)
        } ${chalk.yellowBright(
          contentLength ?? 0
        )} - ${userAgent} ${chalk.yellowBright(ip)} +${chalk.yellow(ms)}ms`
      );
    });
    next();
  }
}
